<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-group"></i> 后台用户管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search.userName" placeholder="用户名" class="handle-input mb10" clearable></el-input>
        <el-date-picker v-model="search.createTimeRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="handle-input mr10" format="YYYY-MM-DD" clearable>
        </el-date-picker>
        <el-button type="primary" icon="el-icon-search" @click="getData()">搜索</el-button>
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="agentLogo" label="头像" width="80">
          <template #default="scope">
            <img v-if="scope.row.agentLogo" :src="scope.row.agentLogo" style="width: 40px; height: 40px; border-radius: 50%;" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="手机号">
          <template #default="scope">
            <span>{{ scope.row.mobile || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮件地址">
          <template #default="scope">
            <span>{{ scope.row.email || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isSingle" label="单点登录">
          <template #default="scope">
            <el-tag :type="scope.row.isSingle ? 'success' : 'info'">
              {{ scope.row.isSingle ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '正常' : '冻结' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间" :formatter="dateFormat"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="text" @click="editPermission(scope.row)">修改权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex" :page-size="query.pageSize" :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>



    <!-- 权限控制弹窗 -->
    <el-dialog title="修改权限" v-model="showPermissionDialog" width="50%" destroy-on-close>
      <div style="margin-bottom: 15px;">
        <strong>用户：</strong>{{ currentUser.userName || '未知用户' }}
      </div>
      <div style="min-height: 200px;">
        <el-tree ref="permissionTree" :data="permissionTreeData" show-checkbox node-key="path" :default-expanded-keys="defaultExpandedKeys" :props="treeProps">
          <template #default="{ data }">
            <span>{{ data.name }}</span>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermissionDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmPermission">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { getUserList, getUserRole, setUserRole } from "@/api/index";
import moment from "moment";

export default {
  inject: ["reload"],
  name: "adminUser",
  data() {
    return {
      query: {
        pageIndex: 1,
        pageSize: 10,
        pageTotal: 0
      },
      tableData: [],
      search: {
        userName: '',
        createTimeRange: []
      },
      currentUser: {},
      // 权限控制相关
      showPermissionDialog: false,
      permissionTreeData: [
        {
          path: '/advertPic',
          name: '广告图片'
        },
        {
          path: '/user',
          name: '用户管理',
          children: [
            {
              path: '/userControl',
              name: '前端用户管理'
            },
            {
              path: '/adminUser',
              name: '后台用户管理'
            },
          ]
        },
        {
          path: '/petManagement',
          name: '宠物管理'
        },
        {
          path: '/content',
          name: '内容管理',
          children: [
            {
              path: "/moments",
              name: "动态管理",
              children: [
                {
                  path: "/blogTopic",
                  name: "动态话题"
                },
                {
                  path: "/blogReply",
                  name: "动态评论"
                },
                {
                  path: "/momentsManagement",
                  name: "动态管理"
                }
              ]
            },
            {
              path: "/community",
              name: "社区管理",
              children: [
                {
                  path: "/forumTopic",
                  name: "帖子话题"
                },
                {
                  path: "/communityClassification",
                  name: "社区分类"
                },
                {
                  path: "/communityManagement",
                  name: "社区管理"
                },
                {
                  path: "/postClassification",
                  name: "帖子分类"
                },
                {
                  path: "/forumReply",
                  name: "帖子评论"
                },
                {
                  path: "/postManagement",
                  name: "帖子管理"
                }
              ]
            },
            {
              path: "/activity",
              name: "活动",
              children: [
                {
                  path: "/activityManagement",
                  name: "活动管理"
                },
                {
                  path: "/activityOrder",
                  name: "活动订单"
                }
              ]
            }

          ]
        },
        {
          path: "/store",
          name: "门店管理"
        },
        {
          path: "/cyBer",
          name: "资金明细"
        }
      ],
      defaultExpandedKeys: ['/content', '/moments', '/community', '/activity'],
      treeProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 时间过滤器
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    // 获取列表数据
    getData() {
      // 处理日期区间
      let startTime = '';
      let endTime = '';
      if (this.search.createTimeRange && this.search.createTimeRange.length === 2) {
        // 格式化日期为 YYYY-MM-DD 格式
        startTime = this.formatDate(this.search.createTimeRange[0]);
        endTime = this.formatDate(this.search.createTimeRange[1]);
      }

      getUserList({
        offset: this.query.pageIndex,
        limit: this.query.pageSize,
        userName: this.search.userName,
        startTime: startTime,
        endTime: endTime
      }).then((res) => {
        if (res.code === 2000) {
          this.tableData = res.data.rows || [];
          this.query.pageTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取数据失败');
        }
      }).catch((error) => {
        this.$message.error('获取数据失败');
        console.error('获取用户列表失败:', error);
      });
    },
    // 分页导航
    handlePageChange(val) {
      this.query.pageIndex = val;
      this.getData();
    },

    // 修改权限
    editPermission(row) {
      this.currentUser = row;
      this.showPermissionDialog = true;

      // 获取用户现有权限
      this.getUserPermissions(row.id);
    },

    // 获取用户现有权限
    getUserPermissions(userId) {
      getUserRole({ id: userId }).then((res) => {
        if (res.code === 2000) {
          // 假设返回的权限数据格式为数组，包含用户已有的权限路径
          const userPermissions = res.data && JSON.parse(res.data) || [];

          // 提取权限路径数组
          const permissionPaths = this.extractPermissionPaths(userPermissions);
          console.log(userPermissions, 77777)

          // 设置权限树的选中状态
          this.$nextTick(() => {
            if (this.$refs.permissionTree) {
              // 先清空所有选中状态
              this.$refs.permissionTree.setCheckedKeys([]);

              // 只设置叶子节点的选中状态，避免父节点自动勾选
              const leafNodes = this.getLeafNodes(permissionPaths);
              this.$refs.permissionTree.setCheckedKeys(leafNodes);
            }
          });
        } else {
          this.$message.error(res.message || '获取用户权限失败');
        }
      }).catch((error) => {
        this.$message.error('获取用户权限失败');
        console.error('获取用户权限失败:', error);
      });
    },

    // 提取权限路径数组
    extractPermissionPaths(permissions) {
      const paths = [];

      const extractPaths = (items) => {
        if (Array.isArray(items)) {
          items.forEach(item => {
            if (item.path) {
              paths.push(item.path);
            }
            if (item.children && item.children.length > 0) {
              extractPaths(item.children);
            }
          });
        }
      };

      extractPaths(permissions);
      return paths;
    },

    // 获取叶子节点（没有子节点的节点）
    getLeafNodes(permissionPaths) {
      const leafNodes = [];

      // 检查每个路径是否为叶子节点
      permissionPaths.forEach(path => {
        const isLeaf = this.isLeafNode(path);
        if (isLeaf) {
          leafNodes.push(path);
        }
      });

      return leafNodes;
    },

    // 判断是否为叶子节点
    isLeafNode(path) {
      const findNode = (nodes, targetPath) => {
        for (let node of nodes) {
          if (node.path === targetPath) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findNode(node.children, targetPath);
            if (found) return found;
          }
        }
        return null;
      };

      const node = findNode(this.permissionTreeData, path);
      return node && (!node.children || node.children.length === 0);
    },

    // 确认权限设置
    confirmPermission() {
      const checkedNodes = this.$refs.permissionTree.getCheckedNodes();
      const checkedKeys = this.$refs.permissionTree.getCheckedKeys();

      // 构建选中的权限树状结构
      const selectedPermissions = this.buildSelectedTree(this.permissionTreeData, checkedKeys);

      console.log('当前用户:', this.currentUser);
      console.log('选中的权限节点:', checkedNodes);
      console.log('选中的权限键值:', checkedKeys);
      console.log('构建的权限树状结构:', selectedPermissions);

      // 调用API保存权限设置
      this.saveUserPermissions(selectedPermissions);
    },

    // 保存用户权限
    saveUserPermissions(permissions) {
      // 调用API保存权限设置
      // 假设保存权限的接口为 /admin/usersRole/setRole
      setUserRole({
        id: this.currentUser.id,
        routing: JSON.stringify(permissions)
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success('权限设置成功');
          this.showPermissionDialog = false;
          this.getData();
        } else {
          this.$message.error(res.message || '权限设置失败');
        }
      }).catch((error) => {
        this.$message.error('权限设置失败');
        console.error('保存用户权限失败:', error);
      });
    },

    // 构建选中的权限树状结构
    buildSelectedTree(treeData, checkedKeys) {
      const buildNode = (nodes) => {
        const selectedNodes = [];

        nodes.forEach(node => {
          if (checkedKeys.includes(node.path)) {
            const newNode = {
              path: node.path,
              name: node.name
            };

            if (node.children && node.children.length > 0) {
              const selectedChildren = buildNode(node.children);
              if (selectedChildren.length > 0) {
                newNode.children = selectedChildren;
              }
            }

            selectedNodes.push(newNode);
          } else if (node.children && node.children.length > 0) {
            // 即使当前节点未选中，也要检查子节点
            const selectedChildren = buildNode(node.children);
            if (selectedChildren.length > 0) {
              const newNode = {
                path: node.path,
                name: node.name,
                children: selectedChildren
              };
              selectedNodes.push(newNode);
            }
          }
        });

        return selectedNodes;
      };

      return buildNode(treeData);
    }

  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-input {
  width: 250px;
  display: inline-block;
  margin-right: 10px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mb10 {
  margin-bottom: 10px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 350px;
}

::v-deep .el-date-editor.el-range-editor {
  width: 350px;
}
</style>
